﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace PSPmmo.LoginServer.Network
{
    class NetworkServer
    {
        TcpListener tcpListener;

        public NetworkServer()
        {
            tcpListener = new TcpListener(IPAddress.Any, 2222);            
        }

        public void Start()
        {
            tcpListener.Start();
            (new Thread(Listen)).Start();
            Console.WriteLine("Server started up.");
        }

        private void Listen()
        {
            while (true)
            {
                TcpClient client = this.tcpListener.AcceptTcpClient();
                Console.WriteLine("new client connected from: {0}", client.Client.RemoteEndPoint);
                Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
                clientThread.Start(client);
            }
        }

        private void HandleClientComm(object client)
        {
            TcpClient tcpClient = (TcpClient)client;
            NetworkStream clientStream = tcpClient.GetStream();

            byte[] message = new byte[4096];
            int bytesRead;

            while (true)
            {
                bytesRead = 0;

                try
                {
                    bytesRead = clientStream.Read(message, 0, 4096);
                }
                catch
                {
                    break;
                }

                if (bytesRead == 0)
                {
                    break;
                }
                bytesRead--;

                new PacketHandler(tcpClient).Handle(new Packet(message, bytesRead));
                Console.WriteLine("Packet recieved from {0}, packet:", tcpClient.Client.RemoteEndPoint);
                //foreach(byte Byte in message)
                //{
                //    Console.Write(Byte);
                //}
            }
            tcpClient.Close();
        }
    }
}
